package com.derbysoft.dswitch.adapter.ihg.web.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public abstract class ApplicationContextAwareHttpServlet extends HttpServlet {

    private static final long serialVersionUID = -676321261100619268L;

    protected final Log logger = LogFactory.getLog(getClass());

    private ApplicationContext webApplicationContext;

    public final void init() throws ServletException {
        getApplicationContext();
    }

    public synchronized ApplicationContext getApplicationContext() {
        if (webApplicationContext == null) {
            webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        }
        if (webApplicationContext == null) {
            throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");
        }
        return webApplicationContext;
    }
}
